<?php
declare (strict_types=1);

namespace app\course\logic\classes\admin;

use app\common\exception\LogicException;
use app\common\library\Queue;
use app\common\logic\category\Category;
use app\course\model\classes\admin\Classes as ClassesModel;
use app\school\model\school\School as SchoolModel;
use app\user\logic\teacher\admin\Teacher;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Model;

/**
 * 后台管理逻辑层
 */
class Classes extends ClassesModel
{
    /**
     * 添加课程
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-15
     *
     * @param array $data 数据
     * @return self
     */
    public function addClasses(array $data)
    {
        $data['mhm_id'] = request()->is_platform ? ($data['mhm_id'] ?? null) : request()->mhm_id;
        // 验证数据
        $this->getValidate()->failException()->check($data);

        $fields = array_keys($this->getFields());

        $data['fullcategorypath']     = $data['cates'] ?? [];
        $data['category']             = $data['cates'] ?? [];
        $data['mhm_category']         = $data['mhm_cates'] ?? [];
        $data['mhm_fullcategorypath'] = $data['mhm_cates'] ?? [];
        $data['ext_data']             = ['headmaster' => $data['headmaster']];
        $data['solo']                 = 1;
        // 有效期
        if (isset($data['term_time']) && is_array($data['term_time'])) {
            $timeData          = $data['term_time'];
            $data['term_time'] = $timeData['type'] == 1 ? intval($timeData['days']) : strtotime($timeData['date']);
        }

        if (!$this->allowField($fields)->data($data, true)->save()) {
            throw new LogicException('添加失败');
        }

        return $this;
    }

    /**
     * 编辑课程
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-15
     *
     * @param array $data 数据
     * @return   self
     */
    public function editClasses(Classes $classes, array $data)
    {
        $data['mhm_id'] = request()->is_platform ? ($data['mhm_id'] ?? null) : request()->mhm_id;
        // 取得验证器
        $this->getValidate()->failException()->check($data);

        $classes->title                = $data['title'];
        $classes->cover                = $data['cover'];
        $classes->fullcategorypath     = $data['cates'];
        $classes->category             = $data['cates'];
        $classes->mhm_fullcategorypath = $data['mhm_cates'] ?? [];
        $classes->mhm_category         = $data['mhm_cates'] ?? [];
        $classes->mhm_id               = $data['mhm_id'];
        $classes->scribing_price       = $data['scribing_price'];
        $classes->price                = $data['price'];
        $classes->status               = $data['status'] ?? 1;
        $classes->info                 = $data['info'];
        $classes->listing_time         = $data['listing_time'];
        $classes->vip_price            = $data['vip_price'];
        $classes->ext_data             = ['headmaster' => $data['headmaster']];
        $classes->is_recommend         = $data['is_recommend'] ?? 0;
        $classes->give_credit          = $data['give_credit'];
        $classes->comment_credit       = $data['comment_credit'];
        $classes->share_credit         = $data['share_credit'];
        // $classes->open_comment         = $data['open_comment'] ?? 0;
        $classes->credit_redeem         = $data['credit_redeem'] ?? 0;
        $classes->credit_redeem_percent = $data['credit_redeem_percent'];
        $classes->solo                  = 1;
        $classes->exam_condition_rate   = $data['exam_condition_rate'] ?? 100;
        $classes->lock                  = $data['lock'] ?? 0;
        $classes->sale_count_market     = $data['sale_count_market'] ?? 0;
        $classes->look_need_login       = $data['look_need_login'] ?? 0;
        $classes->is_marquee            = $data['is_marquee'] ?? 0;
        $classes->onhook_type           = $data['onhook_type'] ?? 0;

        // 有效期
        if (isset($data['term_time']) && is_array($data['term_time'])) {
            $timeData           = $data['term_time'];
            $classes->term_time = $timeData['type'] == 1 ? intval($timeData['days']) : strtotime($timeData['date']);
        }
        if (!$classes->save()) {
            throw new LogicException('编辑失败');
        }

        return $classes;
    }

    /**
     * 编辑指定字段
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-27
     */
    public function editField($id, $field, $value)
    {
        // 信息
        $video = $this->findOrFail($id);

        $video->$field = $value;

        if (!$video->save()) {
            throw new LogicException("更新失败");
        }
        if ('status' === $field) {
            // 队列处理，状态改变通知用户
            Queue::push('CourseNotify', [
                'type'   => 1,
                'source' => $id,
                'value'  => $value,
            ], 30);
        }
        $this->cleanCache($video);

        // 返回值
        return $video;
    }

    /**
     * 点播列表
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-25
     */
    public function classesList($map)
    {
        $list = $this->with(['cover_url'])->where($map)->order('update_time', 'desc')->paginate($this->getListRows());
        return $this->parseList($list);
    }

    /**
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-27
     */
    public function parseList($list)
    {
        foreach ($list as $item) {
            $item->teacher_name = app(Teacher::class)->getTeacherNameById($item->teacher_id);
            $item->school_name  = app(SchoolModel::class)->getSchoolNameById($item->mhm_id);
            // 如果是平台课程，则取平台分类，否则取机构设置的分类
            if ($item->mhm_id == 1) {
                $item->cates = app(Category::class)->parseTitle($item->category, 0, $item->fullcategorypath ?? []);
            } else {
                $item->cates = app(Category::class)->parseTitle($item->mhm_category, 0, $item->mhm_fullcategorypath ?? []);
            }
        }

        return $list;
    }

    /**
     * 删除点播
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-26
     */
    public function deleteClasses($id)
    {
        $classes = $this->where('id', $id)->findOrFail();

        if (!$classes->delete()) {
            throw new LogicException('删除失败');

        }
    }

    /**
     * 批量上架
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/16
     *
     * @param array $ids
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function listingVideos(array $ids = []): void
    {
        $list = $this->whereIn('id', $ids)->select();
        if (!$list->update(['status' => 1, 'listing_time' => Request::time()])) {
            throw new LogicException('操作失败');
        }

    }

    /**
     * 批量禁用
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/16
     *
     * @param array $ids
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function disableVideos(array $ids = []): void
    {
        $list = $this->whereIn('id', $ids)->select();
        if (!$list->update(['status' => 0, 'listing_time' => Request::time() - 1])) {
            throw new LogicException('操作失败');
        }

    }

    /**
     * 批量删除
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/16
     *
     * @param $ids
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function deleteVideos($ids): void
    {
        $list = $this->whereIn('id', $ids)->select();
        if (!$list->delete()) {
            throw new LogicException('操作失败');
        }

    }

    /**
     * 设置课程完结
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/9/26
     *
     * @param $id
     * @return Classes|array|Model
     */
    public function setFinished($id)
    {

        $classed = $this->findOrFail($id);

        $classed->update_status = 0;

        if (!$classed->save()) {
            throw new LogicException("处理失败");
        }

        // 队列处理，状态改变通知用户
        // Queue::push(CourseNotifyJob::class, [
        //     'type'   => 2,
        //     'source' => $id,
        // ], 30);

        return $classed;
    }
}
